package com.newhero.product.module.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.newhero.product.common.controller.BaseController;
import com.newhero.product.common.mybatis.mapper.EntityWrapper;
import com.newhero.product.common.mybatis.mapper.Wrapper;
import com.newhero.product.common.mybatis.toolkit.IdWorker;
import com.newhero.product.common.util.StringUtils;
import com.newhero.product.common.vo.ZTreeModel;
import com.newhero.product.module.sys.model.Organ;
import com.newhero.product.module.sys.service.IOrganService;

/**
 * @ClassName: OrganController
 * @Description: 机构管理控制类
 * @author ymq
 * @date 2017-4-10 上午9:31:23
 */
@Controller
@RequestMapping("/admin")
public class OrganController extends BaseController {

	@Autowired
	private IOrganService organServiceImpl;

	@RequiresPermissions("/admin/organ")
	@RequestMapping(value = "/organ", method = RequestMethod.GET)
	public String organ() {
		return "sys/organ/organ";
	}

	@RequestMapping(value = "/organTree", method = RequestMethod.POST)
	@ResponseBody
	public List<ZTreeModel> organTree(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		EntityWrapper<Organ> wrapper = new EntityWrapper<Organ>();
		wrapper.orderBy("organOrder,organID");
		List<Organ> sysOrganList = organServiceImpl.selectList(wrapper);
		List<ZTreeModel> treeList = new ArrayList<ZTreeModel>();
		for (int i = 0; i < sysOrganList.size(); i++) {
			Organ organ = sysOrganList.get(i);
			String organName = organ.getOrganName();
			ZTreeModel atm = new ZTreeModel(organ.getOrganID(),
					organ.getOrganPID(), organName, true, "");

			if (organ.getOrganType() != null && organ.getOrganType() == 10) {
				atm.setIcon(request.getContextPath()
						+ "/static/zTree_v3/css/ext_icons/building.png");
				
			} else {
				atm.setIcon(request.getContextPath()
						+ "/static/zTree_v3/css/ext_icons/door.png");
			}
			
			if(!"130000000000".equals(organ.getOrganID())){
				atm.setOpen(false);
			}
			
			treeList.add(atm);
		}
		return treeList;
	}

	@RequestMapping(value = "/organForm", method = RequestMethod.GET)
	public String organForm(
			@RequestParam(value = "organID", defaultValue = "", required = false) String organID,
			@RequestParam(value = "organPID", defaultValue = "", required = false) String organPID,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		boolean hasChildren = false;
		if (!organID.equals("")) {
			Organ sysOrgan = organServiceImpl.selectById(organID);
			Wrapper<Organ> wrapper = new EntityWrapper<Organ>();
			wrapper.eq("organPID", organID);
			int count = organServiceImpl.selectCount(wrapper);
			if (count > 0) {
				hasChildren = true;
			}
			model.addAttribute("organData", sysOrgan);
			String organpID = sysOrgan.getOrganPID();
			if (StringUtils.isNotBlank(organpID)) {
				Organ parentOrgan = organServiceImpl.selectById(organpID);
				model.addAttribute("parentOrganID", organPID);
				if (parentOrgan != null
						&& !"".equals(parentOrgan.getOrganName())) {
					model.addAttribute("parentOrganName",
							parentOrgan.getOrganName());
				}
			} else {
				model.addAttribute("parentOrganID", "");
				model.addAttribute("parentOrganName", "顶级");
			}
		} else {
			Map<String, String> emptyOrgan = new HashMap<String, String>();
			emptyOrgan.put("organPID", organPID);
			model.addAttribute("organData", emptyOrgan);
			model.addAttribute("parentOrganID", organPID);
			Organ parentOrgan = organServiceImpl.selectById(organPID);
			if(parentOrgan==null){
				model.addAttribute("parentOrganName", "");
			}else{
				model.addAttribute("parentOrganName", parentOrgan.getOrganName());
			}
			
		}
		model.addAttribute("hasChildren", hasChildren);
		model.addAttribute("organID", organID);
		return "sys/organ/organForm";
	}

	@ResponseBody
	@RequestMapping(value = "/organDelete", method = RequestMethod.POST)
	public Object applicationDelete(
			@RequestParam(value = "organID", required = true) String organID,
			HttpServletRequest request, HttpServletResponse response) {
		organServiceImpl.deleteById(organID);
		return renderSuccess();
	}

	@ResponseBody
	@RequestMapping(value = "/deleteOrganCascade", method = RequestMethod.POST)
	public Object deleteOrganCascade(
			@RequestParam(value = "organID", required = true) String organID,
			HttpServletRequest request, HttpServletResponse response) {
		List<String> idList = organServiceImpl.getIDListByOrganID(organID);
		organServiceImpl.deleteBatchIds(idList);
		return renderSuccess();
	}

	@ResponseBody
	@RequestMapping(value = "/organSave", method = RequestMethod.POST)
	public Object organSave(Organ sysOrgan, HttpServletRequest request,
			HttpServletResponse response) {
		String newguid = "";
		if (sysOrgan.getOrganID() != null && !"".equals(sysOrgan.getOrganID())) {
			newguid = sysOrgan.getOrganID();
		} else {
			newguid = IdWorker.getId();
			sysOrgan.setOrganID(newguid);
		}
		try {
			if (sysOrgan.getOrganPID() != null
					&& !"".equals(sysOrgan.getOrganPID())) {
				Organ preOrgan = organServiceImpl.selectById(sysOrgan
						.getOrganPID());
				sysOrgan.setOrganLevel(preOrgan.getOrganLevel() + 1);
				String pOrganTree = preOrgan.getOrganTree() == null ? ""
						: preOrgan.getOrganTree();
				sysOrgan.setOrganTree(pOrganTree + "|" + newguid);
			}
			organServiceImpl.insertOrUpdate(sysOrgan);
			return renderSuccess();
		} catch (Exception e) {
			logger.error(e);
			return renderError("插入或更新失败！");
		}
	}
}
